package com.lonwin.mes2u8.service;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.google.common.collect.Maps;
import com.lonwin.mes2u8.common.MesConfig;
import com.lonwin.mes2u8.domain.mes.MesCommonResult;
import com.lonwin.mes2u8.domain.mes.MesTokenParam;
import com.lonwin.mes2u8.domain.mes.MesTokenResult;
import com.lonwin.mes2u8.util.MyHttpClientUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Map;
import java.util.Objects;

/**
 * @author DELL
 * @Date 2023-12-15 15:17
 */
@Service
@Slf4j
public class MesTokenService {

    @Resource
    private MesConfig mesConfig;

    /**
     * 获取mes系统的token
     * @return token
     */
    public String getToken() {
        MesTokenParam tokenParam = MesTokenParam.builder().tenantId("SXFXT").username("erp").password("123456").build();
        String responseString = MyHttpClientUtil.sendPostRequest(
                mesConfig.getAddress() + mesConfig.getTokenUrl(),
                Maps.newHashMap(),
                JSONObject.toJSONString(tokenParam),
                MyHttpClientUtil::handleJsonResponse
        );

        MesCommonResult<MesTokenResult> mesTokenResult = JSONObject.parseObject(responseString, new TypeReference<MesCommonResult<MesTokenResult>>(){}.getType());

        if(Objects.isNull(mesTokenResult) || !mesTokenResult.isSuccess()) {
            log.error("get mes token occur exception : response failed [{}]", Objects.nonNull(mesTokenResult) ? mesTokenResult.toString() : "null");
            throw new RuntimeException("get mes token failed");
        }
        MesTokenResult mesTokenResult1 = JSONObject.parseObject(JSONObject.toJSONString(mesTokenResult.getResult()), MesTokenResult.class);

        return mesTokenResult1.getToken();
    }

    public Map<String, String> buildTokenHeader() {
        Map<String, String> tokenMap = Maps.newHashMapWithExpectedSize(1);
        tokenMap.put("X-Access-Token", getToken());

        return tokenMap;
    }
}
